<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" queryCode="searchConditionList"/>
    <TableHeader :can-collapsed="false">
      <template v-slot:left>
        <el-button
          type="primary"
          size="small"
          :icon="CirclePlus"
          @click="onAddItem"
          >新增
        </el-button>
        <el-button
          type="danger"
          size="small"
          :icon="Delete"
          @click="onDeleteItem(selectRows)"
          >删除
        </el-button>
      </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
         
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    />
   
  <Dialog ref="dialog" title="编辑信息" :form-items="formItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="formItems"
        ></BaseForm>
      </template>
  </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import { ElMessage } from 'element-plus';
import {onMounted, reactive, ref } from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { querySearchConditionList,saveSearchCondition,updateSearchCondition,deleteBatchSearchCondition } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { each } from 'lodash';
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableColumns = reactive([
 
  { label: "编号", 
    prop: "code", 
    checked:true,
  },
   { label: "表/视图名", 
    prop: "queryName", 
    checked:true,
  },
   { label: "别名", 
    prop: "aliasName", 
    checked:true,
    width:60,
  },
  { label: "查询字段名", 
    prop: "columnName", 
    checked:true,
  },
   { label: "对象属性名", 
    prop: "propName", 
    checked:true,
  },
  { label: "数据类型", 
    prop: "dataType", 
    checked:true,
  },
 
  { label: "集合内容", 
    prop: "content", 
    checked:true,
    width:540,
  },
  { label: "api(树状)", 
    prop: "api", 
    checked:true,
  },
  

]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    handler: (row: any) => handleEdit(row),
  },
]);

const formItems = reactive([
 
  { label: "编号", 
    type: 'input',
    name: "code", 
    value: '',
    maxlength: 20,
    placeholder: '请输入编号',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
   { label: "表/视图名", 
    type: 'input',
    name: "queryName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入表/视图名',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
 
   { label: "别名", 
    type: 'input',
    name: "aliasName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入别名',
    reset() {
                this.value = "";
            },
  },
  
  { label: "查询字段名", 
    type: 'input',
    name: "columnName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入查询字段名',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "对象属性名", 
    type: 'input',
    name: "propName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入对象属性名',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
   { label: "数据类型", 
    type: 'select',
    name: "dataType", 
    value: 'Input',
    maxlength: 20,
    placeholder: '请选择数据类型',
    selectOptions: [
      {
        label: "文本输入框",
        value: "Input",
      },
       {
        label: "日期",
        value: "Date",
      },
       {
        label: "日期-年月",
        value: "Month",
      },
       {
        label: "数值",
        value: "Number",
      },
        {
        label: "下拉列表",
        value: "Select",
      },
    ],
    reset() {
                this.value = "Input";
            },
  },
  { label: "集合内容", 
    type: 'textarea',
    name: "content", 
    value: '',
    maxlength: 20,
    placeholder: '请输入集合内容',
    reset() {
                this.value = "";
            },
  },
  { label: "", 
    type: 'input',
    name: "searchConditionOid", 
    value: 0,
    maxlength: 20,
    hidden: true,
    reset() {
                this.value = 0;
            },
  },
  { label: "版本号", 
    type: 'input',
    name: "versionNo", 
    value: 0,
    hidden: true,
    reset() {
                this.value = 0;
            },
  },
 
  { label: "api(树状)", 
    type: 'input',
    name: "api", 
    value: '',
    maxlength: 20,
    placeholder: '请输入api(树状)',
    reset() {
                this.value = "";
            },
  },
 

]);
const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propName = item[it.name];
    if(it.name === 'time'){
      let dateRange : any = [];
      // dateRange.push(item['startDate']);
      // dateRange.push(item['endDate']);
      it.value = dateRange;
    }else{
      it.value = propName;
    }
  });
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(updateSearchCondition,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
   let params = {
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(querySearchConditionList,params);
}

function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveSearchCondition,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
  if (data.length > 0) {
    showConfirmBox("是否要删除此数据项，删除后不恢复？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let params: number[] = [];
        data.forEach((item: { searchConditionOid: any }) => {
          params.push(item.searchConditionOid);
        });
        post({
          url: deleteBatchSearchCondition,
          data: {
            keyOids: params,
          },
        })
          .then(() => {
            doRefresh();
            showSuccessMessage("删除成功");
          })
          .catch(console.log);
      })
      .catch(() => {
        showInfoMessage("取消删除");
      });
  } else {
    showErrorMessage("请选择要删除的数据项");
  }
}

function searchForm(data: any) {
    let params = {
    searchConditionVOList: data,
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(querySearchConditionList,params);
}

function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}

onMounted(doRefresh);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
